<?php

namespace addons\kuerp\controller;

use addons\kuerp\library\Wechat;
use addons\kuerp\model\Staff;
use addons\kuerp\model\StaffRole;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use addons\kuerp\model\Field;
use addons\kuerp\model\Form;
use addons\kuerp\model\StaffRule;
use addons\kuerp\model\AdminConfig;
use addons\kuerp\model\Admin;
use fast\Http;
use think\App;
use think\Cache;
use think\Config;
use think\Hook;
use think\Db;

/**
 * 公共接口
 */
class Common extends StaffApi {
	protected $noNeedLogin = ['init','getConfig','getGeocoder'];
	protected $noNeedRight = '*';


	/**
	 * 加载初始化
	 * @param string $version 版本号
	 * @param string $lng 经度
	 * @param string $lat 纬度
	 */
	public function init() {
		if ($version = $this->request->request('version')) {
			$lng = $this->request->request('lng');
			$lat = $this->request->request('lat');

			//配置信息
			$upload = Config::get('upload');
			//如果非服务端中转模式需要修改为中转
			if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
				//临时修改上传模式为服务端中转
				set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

				$upload = \app\common\model\Config::upload();
				// 上传信息配置后
				Hook::listen("upload_config_init", $upload);

				$upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
			}

			$upload['cdnurl']    = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
			$upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

			$content = [
				'citydata'    => Area::getCityFromLngLat($lng, $lat),
				'versiondata' => Version::check($version),
				'uploaddata'  => $upload,
				'coverdata'   => Config::get("cover"),
			];
			$this->success('', $content);
		} else {
			$this->error(__('Invalid parameters'));
		}
	}


	/**
	 * 上传文件
	 * @ApiMethod (POST)
	 * @param File $file 文件流
	 */
    public function upload()
    {
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $name = input('name');
        try {

            $upload = new Upload($file);
            $attachment = $upload->upload(null);
            if (stristr($attachment->mimetype, 'image')) {
                $types = 'image';
            } else {
                $types = 'file';
            }
            $staff = Staff::info();
            $params = array(
                'name' => $name ?: $attachment->filename,
                'save_name' => $attachment->url,
                'size' => $attachment->filesize,
                'types' => $types,
                'file_path' => $attachment->url,
                'create_staff_id' => empty($staff) ? 0 : $staff->id
            );
            $attachment = new \addons\kuerp\model\File();
            $attachment->data(array_filter($params));
            $attachment->save();

            $fileId = $attachment->id;

        } catch (UploadException $e) {
            return json_encode(['code' => 0, 'msg' => $e->getMessage()]);
        }
        $this->success(__('Uploaded successful'), [
            'id' => $fileId,
            'name' => $params['name'],
            'url' => cdnurl($attachment->file_path, true),
            'types' => $types,
            'path' => $attachment->file_path
        ]);
    }


	//select 字段表
	public function selectOption() {
		$fields = [];//Field::where([])->select();
		$data   = [];
        foreach ($fields as $v) {
            $data[$v['type']][$v['name']] = json_decode($v['data']);
        }
        //获取客户等级 客户分类 客户状态
        $customerLevels = Db::name('kuerp_customerlevel')->where('status', '1')->column('id,name');
        $customertype = Db::name('kuerp_customertype')->where('status', '1')->column('id,type_name as name');
        $customerfollow = config('site.customer_follow_status');
        $data['customer'] = [
            'level' => $customerLevels,
            'type' => $customertype,
            'follow' => $customerfollow
        ];
        $data['other'] = [
            'follow_type' => config('site.follow_type')
        ];
        $this->success('请求成功', $data);
	}


	//获取form表单
	public function getForm() {
		$type = input('type', 'customer');//leads 线索 customer 客户 contacts 联系人 contract 合同 examine回款 product产品
		$form = Form::where(['type' => $type])->find();

		$this->success('请求成功', json_decode($form['data'], true));
	}


	//获取员工
	public function getSelectStaff() {
		$name  = input('name');
		$department_id = input('department_id');
		$stafftype = input('stafftype');

		$where = ['status' => '1'];
		if ($name) {
			$where['name|phone'] = ['like', "%{$name}%"];
		}
		// if ($department_id) {
		// 	$where['department_id'] = ['in',explode(',',$department_id)];
		// }

        if($stafftype == 'staff'){
            $staffs = \addons\kuerp\model\StaffMember::where($where)->field('id,name,phone as mobile,admin_id')->select();
            if ($staffs) {
                $adminids = array_column($staffs, 'admin_id');
                $adminlist = Admin::where('id', 'in', $adminids)->column('avatar,nickname', 'id');
                foreach ($staffs as &$staff) {
                    $staff['img'] = $adminlist[$staff['admin_id']]['avatar'];
                    $staff['img'] = $staff['img'] ? cdnurl($staff['img'], true) : '';
                    $staff['nickname'] = $adminlist[$staff['admin_id']]['nickname'];
                }
            }
        }else{
            $staffs = Admin::where(['deletetime'=>null,'status'=>'normal'])->where('id > 1')->field('id,avatar as img,mobile,nickname,nickname as name')->select();
            foreach ($staffs as &$staff) {
                $staff['img'] = $staff['img'] ? cdnurl($staff['img'], true) : '';
            }
        }


		$this->success('请求成功', $staffs);
	}

    //获取员工权限
    public function getStaffRule(){
        $staff_id= $this->auth->id;
        $staff=\addons\kuerp\model\Admin::get($staff_id);
        // $role=StaffRole::where(['id'=>$staff['role']])->find();
        // $rules=isset($role['rules'])?explode(',',$role['rules']):[];
        // $row=StaffRule::where(['pid'=>0])->column('name','id');
        // $staffRules=StaffRule::where(['pid'=>['neq',0],'type'=>['neq','data']])->select();
        //是否需要开启积分申请
        $score_config = \app\common\model\caijiatong\ShoproConfig::getScoreConfig();
        $is_enable_score = $score_config['consume_get_score'] ?? 0;
        $roleList=[
            'menu' => [
                'contract' => [
                    'name' => '订单',
                    'is_show' => 1
                ],
                'sign_in' => [
                    'name' => '拜访签到',
                    'is_show' => 1
                ],
                'map' => [
                    'name' => '地图',
                    'is_show' => 1
                ],
                'product' => [
                    'name' => '商品',
                    'is_show' => 1
                ],
                'expense' => [
                    'name' => '报销单',
                    'is_show' => 1
                ],
                'serial' => [
                    'name' => '锁号',
                    'is_show' => 1
                ],
                'scoreapply' => [
                    'name' => '积分申请',
                    'is_show' => $is_enable_score ? 1 : 0
                ],
                'commonseal' => [
                    'name' => '公章申请',
                    'is_show' => 1
                ],
            ]
        ];
        // foreach ($staffRules as $v) {
        //     $pname = $row[$v['pid']] ?? '';
        //     if ($pname == 'menu') {
        //         $roleList[$pname][$v['name']] = [
        //             'name' => $v['title'],
        //             'is_show' => in_array($v['id'], $rules) ? 1 : 0
        //         ];
        //     } else {
        //         $roleList[$pname][$v['type']][$v['name']] = [
        //             'name' => $v['title'],
        //             'is_show' => in_array($v['id'], $rules) ? 1 : 0
        //         ];
        //     }
        // }
        $this->success('请求成功',$roleList);
    }

    /**
     * 设置数据缓存
     */
    public function setCacheData()
    {

        $type = input('type');
        $id = $this->auth->id;
        $params = $this->request->post();
        unset($params['type']);
        Cache::set($type . $id, json_encode($params), 60*60 * 3);
        $this->success('设置成功');
    }

    /**
     * 读取数据缓存
     */
    public function getCacheData()
    {
        $type = input('type');
        $id = $this->auth->id;
        $data=json_decode(Cache::get($type . $id),true);
        if(empty($data)){
            $data=null;
        }
        $this->success('获取成功', $data);
    }

    /**
     * 获取后台配置
     */
    public function getConfig(){
        $map_key = AdminConfig::getConfigValue('map_key','wechat');
        $mobile_name =AdminConfig::getConfigValue('user_name','user');
        // $map_key = '64YBZ-BTKRA-2UUKZ-C66O2-SKVJ6-7YFE2';//config('wx.map_key');
        $wechat = new Wechat('wxMiniProgram');
        $appid = $wechat->config['app_id'];
        // $mobile_name = config('wx.title');
        $logo = config('site.logo');
        $data=[
            'map_key'=>$map_key ? $map_key : '',
            'appid'=>$appid ? $appid : '',
            'mobile_name'=>$mobile_name? $mobile_name :'新标杆CRM',
            'logo' => $logo ? cdnurl($logo, true) : '',
        ];
        $this->success('请求成功',$data);
    }

    /**
     * 逆解析
     */
    public function getGeocoder(){
        $map_key= AdminConfig::getConfigValue('map_key','wechat');
        if(empty($map_key)){
            $this->error('腾讯地图key未设置，请联系管理员设置！');
        }
        $lat=input('lat');
        $lng=input('lng');
        if(empty($lat) || empty($lng)){
            $this->error('经度或纬度不能为空');
        }
        $url='https://apis.map.qq.com/ws/geocoder/v1/';
        $params = ['location' => $lat.','.$lng, 'get_poi' => 1, 'key' => $map_key];
        $result=Http::get($url,$params);
        $result=json_decode($result);
        $this->success('请求成功',$result);
    }
    /**
     *省市区转地址
     */
    public function addressGeocoder(){
        $map_key= AdminConfig::getConfigValue('map_key','wechat');
        if(empty($map_key)){
            $this->error('腾讯地图key未设置，请联系管理员设置！');
        }
        $address=input('address');
        $address = urlencode($address);
        $url="https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&key={$map_key}";
        $result=file_get_contents($url);
        $result=json_decode($result,true);

        $this->success('请求成功',$result);
    }

    /**
     * 获取时间
     */
    public function getTimes()
    {
        $times = input('times');
        $times = setTimes($times, 'date');
        $this->success('请求成功', ['times' => $times]);
    }

    /**
     * 获取搜索字段
     */
    public function getSearchFields(){
        $type=input('type');//leads
        $fields= [];//FormField::where(['types'=>$type,'list_show'=>1,'info_type'=>'main'])->select();
        $this->success('请求成功',$fields);
    }

    public function getCitys()
    {
        $area = Db::name('area') // 指定数据表名
        ->field('id,name,pid,level') // 指定查询返回的字段
        ->select(); // 执行查询并返回结果
        $area = $this->getTree($area);
        $this->success('请求成功',$area);
    }

    //无限递归分类
    function getTree($arr, $fid = 0)
    {
        $newArr = array();
        foreach ($arr as $v) {
            if ($v["pid"] == $fid) {
                $children = $this->getTree($arr, $v['id']);
                $node = array(
                    "value" => $v['id'],
                    "name" => $v['name'],
                    "districts" => []
                );

                if (!empty($children)) {
                    $node["districts"] = $children;
                }
//                if (isset($v["level"]) && $v["level"] == 2) {
//                    // 将二级节点本身作为自己的一条子集
//                    $subNode = array(
//                        "value" => $v['id'],
//                        "name" => $v['name'],
//                        "districts" => null,
//                    );
//                    array_unshift($node["districts"], $subNode); // 将子集插入到最前面
//                }
                // 如果 children 数组为空，将其改为 null
                if (count($node["districts"]) == 0) {
                    $node["districts"] = null;
                }
                $newArr[] = $node;
            }
        }
        return $newArr;
    }
}
